package com.lagou.userservice.controller;

import com.lagou.common.User;
import com.lagou.userservice.feign.RemoteCodeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @author zhangxuyuan
 * @version 1.0
 * @date 2021/1/14
 */
@RestController
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteCodeService remoteCodeService;

    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable("email")String email)
    {
        return redisTemplate.hasKey(email);
    }

    @GetMapping("/login/{email}/{password}")
    public Object login(@PathVariable("email")String email,
                        @PathVariable("password")String password)
    {
        User user =(User) redisTemplate.opsForValue().get(email);
        if(user==null || !StringUtils.equals(user.getPassword(),password))
        {
            return false;
        }
        else
        {
            return user.getEmail()+"-"+user.getPassword();
        }
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable("token")String token, HttpServletResponse response)
    {
        int i = token.indexOf("-");
        String email=token.substring(0,i);
        User user =(User) redisTemplate.opsForValue().get(email);
        if(user!=null)
        {
            return user.getEmail();
        }
        else
        {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return "no user";
        }
    }
    //注册
    @GetMapping("/register/{email}/{password}/{code}")
    public Integer register(@PathVariable("email")String email,
                        @PathVariable("password")String password,
                        @PathVariable("code")String code)
    {   //校验验证码
        Integer validate = remoteCodeService.validate(email, code);
        if(validate.equals(0))
        {
            redisTemplate.opsForValue().set(email,
                new User(email,password,null,null,null));
        }
        return validate;
    }
}
